﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PropertyAttribute.cs" company="CodePlex">
//   The MIT License
//   Copyright (c) 2013 Julien Blin
//   
//   Permission is hereby granted, free of charge, to any person obtaining a copy
//   of this software and associated documentation files (the "Software"), to deal
//   in the Software without restriction, including without limitation the rights
//   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is
//   furnished to do so, subject to the following conditions:
//   
//   The above copyright notice and this permission notice shall be included in
//   all copies or substantial portions of the Software.
//   
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//   THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace UCodeFirst
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;

    using UCodeFirst.ContentTypes;
    using UCodeFirst.DataTypes;

    using Umbraco.Core;
    using Umbraco.Core.Models;

    /// <summary>
    /// Allows the definition of property attributes.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public sealed class PropertyAttribute : NameAttributeBase
    {
        /// <summary>
        /// The data type name.
        /// </summary>
        private readonly string dataTypeName;

        /// <summary>
        /// The default data type.
        /// </summary>
        private readonly UmbracoDefaultDataType defaultDataType;

        /// <summary>
        /// The tab.
        /// </summary>
        private readonly Enum tab;

        /// <summary>
        /// The data type base.
        /// </summary>
        private readonly Type dataTypeBase;

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyAttribute"/> class
        /// by specifying a default Umbraco data type.
        /// </summary>
        /// <param name="defaultDataType">
        /// The default data type.
        /// </param>
        /// <param name="tab">
        /// The tab (or property group) that this property belongs to.
        /// It must be an <see cref="Enum"/>, and the <see cref="Enum"/> value will determine the order.
        /// </param>
        public PropertyAttribute(UmbracoDefaultDataType defaultDataType, object tab)
            : this()
        {
            this.defaultDataType = defaultDataType;
            this.tab = (Enum)tab;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyAttribute"/> class
        /// by specifying a type of <see cref="dataTypeBase"/>.
        /// </summary>
        /// <param name="dataTypeBase">
        /// Must be assignable from <see cref="dataTypeBase"/>.
        /// </param>
        /// <param name="tab">
        /// The tab (or property group) that this property belongs to.
        /// It must be an <see cref="Enum"/>, and the <see cref="Enum"/> value will determine the order.
        /// </param>
        public PropertyAttribute(Type dataTypeBase, object tab)
            : this()
        {
            this.dataTypeBase = dataTypeBase;
            this.tab = (Enum)tab;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyAttribute"/> class
        /// by specifying a name for the data type.
        /// </summary>
        /// <param name="dataTypeName">
        /// Name of the data type
        /// </param>
        /// <param name="tab">
        /// The tab (or property group) that this property belongs to.
        /// It must be an <see cref="Enum"/>, and the <see cref="Enum"/> value will determine the order.
        /// </param>
        public PropertyAttribute(string dataTypeName, object tab)
            : this()
        {
            this.dataTypeName = dataTypeName;
            this.tab = (Enum)tab;
        }

        /// <summary>
        /// Prevents a default instance of the <see cref="PropertyAttribute"/> class from being created.
        /// </summary>
        private PropertyAttribute()
        {
            this.Mandatory = DefaultValues.Mandatory;
            this.Description = DefaultValues.Description;
            this.Validation = DefaultValues.Validation;
        }

        /// <summary>
        /// Gets or sets a value indicating whether the property is mandatory.
        /// Default is false.
        /// </summary>
        public bool Mandatory { get; set; }

        /// <summary>
        /// Gets or sets the validation regular expression.
        /// </summary>
        public string Validation { get; set; }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// Gets or sets the custom converter. If not specified, the <see cref="StandardConverters"/>
        /// will try to use a standard converter.
        /// </summary>
        public Type Converter { get; set; }

        /// <summary>
        /// Gets the data type definition.
        /// </summary>
        /// <returns>
        /// The <see cref="IDataTypeDefinition"/>.
        /// </returns>
        /// <exception cref="UCodeFirstException">
        /// If not found.
        /// </exception>
        internal IDataTypeDefinition GetDataTypeDefinition()
        {
            IDataTypeDefinition result;
            var dataTypeService = ApplicationContext.Current.Services.DataTypeService;
            
            if (!string.IsNullOrEmpty(this.dataTypeName))
            {
                result = dataTypeService.GetAllDataTypeDefinitions().FirstOrDefault(x => x.Name.InvariantEquals(this.dataTypeName));
                if (result == null)
                {
                    throw new UCodeFirstException(Resources.UnableToFindDataType.InvariantFormat(this.dataTypeName));
                }

                return result;
            }

            if (this.dataTypeBase != null)
            {
                var dataTypeNameFromDataType = this.dataTypeBase.GetAttr<DataTypeAttribute>().GetName(this.dataTypeBase.Name);
                result = dataTypeService.GetAllDataTypeDefinitions().FirstOrDefault(x => x.Name.InvariantEquals(dataTypeNameFromDataType));
                if (result == null)
                {
                    throw new UCodeFirstException(Resources.UnableToFindDataType.InvariantFormat(dataTypeNameFromDataType));
                }

                return result;
            }
            
            result = dataTypeService.GetDataTypeDefinitionById((int)this.defaultDataType);
            if (result == null)
            {
                throw new UCodeFirstException(Resources.UnableToFindDataType.InvariantFormat(this.defaultDataType));
            }

            return result;
        }

        /// <summary>
        /// Gets the group (tab) name.
        /// </summary>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        internal string GetGroupName()
        {
            var tabMemberInfo = this.tab.GetType().GetMember(this.tab.ToString()).First();
            return tabMemberInfo.HasAttr<EnumNameAttribute>() ? tabMemberInfo.GetAttr<EnumNameAttribute>().Name : this.tab.ToString();
        }

        /// <summary>
        /// Gets the group (tab) name.
        /// </summary>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        internal int GetGroupOrder()
        {
            return Convert.ToInt32(this.tab);
        }

        /// <summary>
        /// Holds default values.
        /// </summary>
        public static class DefaultValues
        {
            /// <summary>
            /// false
            /// </summary>
            [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1630:DocumentationTextMustContainWhitespace", Justification = "Reviewed. Suppression is OK here.")]
            public const bool Mandatory = false;

            /// <summary>
            /// Empty string.
            /// </summary>
            public const string Description = @"";

            /// <summary>
            /// Empty string.
            /// </summary>
            public const string Validation = @"";
        }
    }
}
